package com.rundatop.wx.controller;


import static com.rundatop.wx.util.WxResponseCode.AUTH_CAPTCHA_FREQUENCY;
import static com.rundatop.wx.util.WxResponseCode.AUTH_CAPTCHA_UNMATCH;
import static com.rundatop.wx.util.WxResponseCode.AUTH_INVALID_ACCOUNT;
import static com.rundatop.wx.util.WxResponseCode.AUTH_INVALID_MOBILE;
import static com.rundatop.wx.util.WxResponseCode.AUTH_MOBILE_REGISTERED;
import static com.rundatop.wx.util.WxResponseCode.AUTH_MOBILE_UNREGISTERED;
import static com.rundatop.wx.util.WxResponseCode.AUTH_NAME_REGISTERED;
import static com.rundatop.wx.util.WxResponseCode.AUTH_OPENID_UNACCESS;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.rundatop.core.util.CharUtil;
import com.rundatop.core.util.JacksonUtil;
import com.rundatop.core.util.RegexUtil;
import com.rundatop.core.util.ResponseUtil;
import com.rundatop.core.util.bcrypt.BCryptPasswordEncoder;
import com.rundatop.dao.model.User;
import com.rundatop.wx.annotation.LoginUser;
import com.rundatop.wx.config.WxProperties;
import com.rundatop.wx.dto.UserInfo;
import com.rundatop.wx.dto.WxLoginInfo;
import com.rundatop.wx.service.UserService;
import com.rundatop.wx.service.UserTokenManager;
import com.rundatop.wx.wechat.utils.WxHelper;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;


/**
 * 鉴权服务
 */
@RestController
@RequestMapping("/wx/auth")
public class WxAuthController extends BaseController {
    private final Log logger = LogFactory.getLog(WxAuthController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private WxMaService wxService;

    /**
     * 账号登录
     *
     * @param body    请求内容，{ username: xxx, password: xxx }
     * @param request 请求对象 
     * @return 登录结果
     */
//    @PostMapping("login")
//    public Object login(@RequestBody String body, HttpServletRequest request) {
//        String username = JacksonUtil.parseString(body, "username");
//        String password = JacksonUtil.parseString(body, "password");
//        if (username == null || password == null) {
//            return ResponseUtil.badArgument();
//        }
//
//        User user = userInfoService.queryByUsername(username);
//        if (user == null) {
//            return ResponseUtil.fail(AUTH_INVALID_ACCOUNT, "账号不存在");
//        }
//
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        if (!encoder.matches(password, user.getPassword())) {
//            return ResponseUtil.fail(AUTH_INVALID_ACCOUNT, "账号密码不对");
//        }
//
//        // 更新登录情况
////        user.setLastLoginTime(LocalDateTime.now());
////        user.setLastLoginIp(IPUtil.getIpAddr(request));
////        if (userService.updateNotNull(user) == 0) {
////            return ResponseUtil.updatedDataFailed();
////        }
//
//        // userInfo
//        UserInfo userInfo = new UserInfo();
//        userInfo.setNickName(user.getNickName());
//        userInfo.setPhone(user.getPhone());
//        userInfo.setAvatarUrl(user.getHeadImg());
//        userInfo.setIdCard(user.getIdCard());
//
//        // token
//        String token = UserTokenManager.generateToken(user.getId());
//
//        Map<Object, Object> result = new HashMap<Object, Object>();
//        result.put("token", token);
//        result.put("userInfo", userInfo);
//        return ResponseUtil.ok(result);
//    }
     
    /**
      * 检查是否有效并返回个人信息及新token
     * <p>
     *
     * @param userId 用户ID
     * @return 用户个人数据
     */
    @GetMapping("checkToken")
    public Object checkToken(@LoginUser String userId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        User user =userService.getById(userId);
        if(null==user) {
        	ResponseUtil.fail(AUTH_INVALID_ACCOUNT, "账号不存在");
        }
     // userInfo
        UserInfo userInfo = new UserInfo();
        userInfo.setNickName(user.getNickName());
        userInfo.setPhone(user.getPhone());
        userInfo.setHeadImg(user.getHeadImg());
        userInfo.setId(user.getId());
        userInfo.setF1(user.getF1());
//        userInfo.setIdCard(user.getIdCard());

        // token
        String token = UserTokenManager.generateToken(userId);

        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("token", token);
        result.put("userInfo", userInfo);
        return ResponseUtil.ok(result);
    }

	
    @PostMapping("logout")
    public Object logout(@LoginUser Integer userId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        return ResponseUtil.ok();
    }

}
